import 'package:flutter/cupertino.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:uuid/uuid.dart';

import '../../../data/db/models/bt_order.dart';
import '../../../data/db/providers/bt_order_provider.dart';
import '../../../data/models/bt_product.dart';
import '../../../data/store/bt_hive_logon_store.dart';
import '../../../data/store/bt_logon_data.dart';
import '../../utils/bt_constants.dart';
import '../../utils/bt_event_bus.dart';
import '../repository/bt_discover_repository.dart';

class BtDiscoverModel extends ChangeNotifier {
  final int _pageSize = 20;

  final PagingController<int, BtProduct> _pagingController = PagingController(firstPageKey: 0);

  PagingController<int, BtProduct> get pagingController => _pagingController;

  late PageRequestListener<int> _listener;

  late final BtDiscoverRepository repository;

  int _availableCoins = 0;

  int get availableCoins => _availableCoins;

  BtDiscoverModel() {
    repository = BtDiscoverRepository();
    BtHiveLogonStore().getData().then((result) {
      _availableCoins = result?.availableCoins ?? 0;
      notifyListeners();
    });
    _listener = (pageKey) {
      pageKey++;
      buildBtGoodsList(pageKey);
    };
    _pagingController.addPageRequestListener(_listener);

    eventBus.on<BtEventFn>().listen((event) {
      if (event.refresh == freshAvailableCoins) {
        BtHiveLogonStore().getData().then((result) {
          _availableCoins = result?.availableCoins ?? 0;
          notifyListeners();
        });
      }
    });
  }

  void consume(int outlay, Function(bool success, String msg, String orderNo) onResult) {
    if (_availableCoins >= outlay) {
      repository.reviewModeConsume(outlay, (success, msg) {
        var uuid = const Uuid();
        String randomOrderNo = uuid.v4();
        if (success) {
          _subtractCoins(outlay);
          _saveOrder(randomOrderNo);
        }
        onResult(success, msg, randomOrderNo);
      });
    } else {
      onResult(false, 'Insufficient coins', '');
    }
  }

  void _saveOrder(String orderNo) {
    BtOrderProvider().insert(BtOrder(
      goodsCode: '',
      goodsName: '',
      orderNo: orderNo,
      payAmount: '0.0',
      paidAmount: ' 0.0',
      paidCurrency: '',
    ));
  }

  Future<void> _subtractCoins(int coins) async {
    var data = await BtHiveLogonStore().getData();
    BtHiveLogonStore().putData(BtLogonData(
      token: data!.token,
      userId: data.userId,
      userType: data.userType,
      nickname: data.nickname,
      avatarUrl: data.avatarUrl,
      avatarThumbUrl: data.avatarThumbUrl,
      loginPkgName: data.loginPkgName,
      country: data.country,
      birthday: data.birthday,
      availableCoins: data.availableCoins - coins,
    ));
    _availableCoins = data.availableCoins - coins;

    notifyListeners();
  }

  void buildBtGoodsList(int pageKey) {
    try {
      final List<BtProduct> newItems = [];
      newItems.add(const BtProduct(
        productId: '1',
        name: 'vinyl record',
        coin: 66,
        cover: 'assets/images/posts/bt_cap_pexels_chevanon.jpg',
      ));
      newItems.add(const BtProduct(
        productId: '2',
        name: 'Read books',
        coin: 68,
        cover: 'assets/images/posts/bt_am_pexels_john.jpg',
      ));
      newItems.add(const BtProduct(
        productId: '3',
        name: 'Random Coffee',
        coin: 88,
        cover: 'assets/images/posts/bt_am_pexels_ariel.jpg',
      ));
      newItems.add(const BtProduct(
        productId: '4',
        name: 'The Random Band',
        coin: 108,
        cover: 'assets/images/posts/bt_am_pexels_skylar.jpg',
      ));
      final isLastPage = newItems.length < _pageSize;
      if (isLastPage) {
        _pagingController.appendLastPage(newItems);
      } else {
        _pagingController.appendPage(newItems, pageKey);
      }
    } catch (error) {
      _pagingController.error = error;
    }
  }
}
